const express = require('express');
const router = express.Router();
const { Article } = require('../../models');
const { Op } = require('sequelize');
const { NotFoundError } = require('../../utils/errors');
const { success, failure } = require('../../utils/responses');

/**
 * 公共方法：查询当前文章
 */
async function getArticle(req) {
   // 获取文章 ID
  const { id } = req.params;

   // 查询当前文章
  const article = await Article.findByPk(id);

  // 如果没有找到，就抛出异常
  if (!article) {
    throw new NotFoundError(`ID: ${ id }的文章未找到。`)
  }

  return article;
}
/**
 * 公共方法：白名单过滤
 * @param req
 * @returns {{title, content: (string|string|DocumentFragment|*)}}
 */
function filterBody(req) {
  return {
    title: req.body.title,
    content: req.body.content
  };
}
/**
 * 查询文章列表
 * GET /admin/articles
 */
router.get('/', async function (req, res) {
  try {
    // 定义查询条件
   
      const { title , page , size} = req.query; 

      if (title) {
        // 模糊搜索
        condition.where = { title: { [Op.like]: `%${title}%` } };
      }
      const pageNum = page ? page : 1;
      const condition = {
          order: [['id', 'DESC']],
          offset: Number((pageNum - 1) * size),
          limit: Number(size)
      };
    // 查询数据
    const  { count, rows } = await Article.findAndCountAll(condition);

    // 返回查询结果
    success(res, '查询文章列表成功。', {
      articles: rows,
      pagination: {
        total: count,
        page,
        size,
      }
    });
  } catch (error) {
    // 返回错误信息
    failure(res, error);
  }
});
/**
 * 查询文章详情
 */
router.get('/:id', async function (req, res) {
    try {
        const article = await getArticle(req);
        success(res, '查询文章成功。', { article });
        
    } catch (error) {
        failure(res, error);
    }
})
 /**
  * 创建文章
  */
router.post("/", async function (req, res) {
    try {
        const body = filterBody(req);
        const article = await Article.create(body);
        success(res, '创建文章成功。', { article }, 201);
    } catch (error) {
      failure(res, error);

    }
})
/**
 * 删除文章
 */
router.delete('/:id', async function (req, res) {
    try {
        const article = await getArticle(req);
        await article.destroy()
        success(res, '删除文章成功。');
        
    } catch (error) {
        failure(res, error);
    }
})
/**
 * 更新文章
 */
router.put('/:id', async function (req, res) {
    try {
        const article = await getArticle(req);
        const body = filterBody(req);
        await article.update(body)
        success(res, '更新文章成功。', { article });
        
    } catch (error) {
        failure(res, error);
    }
})
module.exports = router;
